/*
 * Project: Payment
 * Document: MerchantManager
 * Date: 2020/8/18 5:07 下午
 * Author: wangbz
 *
 * Copyright © 2020 www.ixiachong.com Inc. All rights reserved.
 * 注意：本内容仅限于深圳瞎充集团有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.factory;

import lombok.Builder;
import lombok.Getter;
import lombok.extern.java.Log;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

@Log
@Builder
public class MerchantManager<M> {
    private final Map<String, M> merchantConfigOfNo = new ConcurrentHashMap<>();
    private Function<String, Map<String, String>> configFinder;
    private Function<Context, M> merchantSupplier;

    public M get(String no) {
        return merchantConfigOfNo.computeIfAbsent(no, merchantNo -> merchantSupplier.apply(Context.builder()
                .no(merchantNo)
                .configs(configFinder.apply(merchantNo))
                .build()
        ));
    }

    public void release(String no) {
        merchantConfigOfNo.remove(no);
    }

    @Getter
    @Builder
    public static class Context {
        private String no;
        private Map<String, String> configs;
    }
}
